// <copyright file="MenuScreen.cs" company="SpaceRock Team Members">
// Project: SpaceRock
// File: MenuScreen.cs (8,03 KB, 230 lines)
// Creation date: 2010-05-28 13:53
// Last modified: 2010-06-11 20:21
// </copyright>

#region Using directives
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Graphics;
using System;
using System.Collections.Generic;
#endregion

namespace XnaGameFramework.GameStateManagement
{
    /// <summary>
    /// Base class for screens that contain a menu of options. The user can
    /// move up and down to select an entry, or cancel to back out of the screen.
    /// </summary>
    abstract class MenuScreen : GameScreen
    {
        /// <summary>
        /// Title background texture
        /// </summary>
        private Texture2D titleBackgroundTexture;

        /// <summary>
        /// Menu entries
        /// </summary>
        private List<MenuEntry> menuEntries = new List<MenuEntry>();
        
        /// <summary>
        /// Selected entry
        /// </summary>
        private int selectedEntry = 0;
        
        /// <summary>
        /// Menu title
        /// </summary>
        private string menuTitle;

        /// <summary>
        /// _On select entry sound
        /// </summary>
        private SoundEffect _OnSelectEntrySound;

        /// <summary>
        /// _On item selected sound
        /// </summary>
        private SoundEffect _OnItemSelectedSound;

        /// <summary>
        /// Gets the list of menu entries, so derived classes can add
        /// or change the menu contents.
        /// </summary>
        protected IList<MenuEntry> MenuEntries
        {
            get { return menuEntries; }
        } // MenuEntries

        /// <summary>
        /// Constructor.
        /// </summary>
        public MenuScreen(string menuTitle)
        {
            this.menuTitle = menuTitle;

            TransitionOnTime = TimeSpan.FromSeconds(0.5);
            TransitionOffTime = TimeSpan.FromSeconds(0.5);
        } // MenuScreen

        /// <summary>
        /// Load content
        /// </summary>
        public override void LoadContent()
        {
            titleBackgroundTexture = ScreenManager.Game.Content.Load<Texture2D>("Images/menuButtonBg");
            _OnSelectEntrySound = ScreenManager.Game.Content.Load<SoundEffect>("Sounds/MenuClick");
            _OnItemSelectedSound = ScreenManager.Game.Content.Load<SoundEffect>("Sounds/MenuItemSelected");
            base.LoadContent();
        } // LoadContent

        /// <summary>
        /// Responds to user input, changing the selected entry and accepting
        /// or cancelling the menu.
        /// </summary>
        public override void HandleInput(InputState input, GameTime gameTime)
        {
            // Move to the previous menu entry?
            if (input.IsMenuUp(ControllingPlayer))
            {
                _OnItemSelectedSound.Play();
                selectedEntry--;

                if (selectedEntry < 0)
                    selectedEntry = menuEntries.Count - 1;
            }

            // Move to the next menu entry?
            if (input.IsMenuDown(ControllingPlayer))
            {
                _OnItemSelectedSound.Play();
                selectedEntry++;

                if (selectedEntry >= menuEntries.Count)
                    selectedEntry = 0;
            }

            // Accept or cancel the menu? We pass in our ControllingPlayer, which may
            // either be null (to accept input from any player) or a specific index.
            // If we pass a null controlling player, the InputState helper returns to
            // us which player actually provided the input. We pass that through to
            // OnSelectEntry and OnCancel, so they can tell which player triggered them.
            PlayerIndex playerIndex;

            if (input.IsMenuSelect(ControllingPlayer, out playerIndex))
                OnSelectEntry(selectedEntry, playerIndex);
            else if (input.IsMenuCancel(ControllingPlayer, out playerIndex))
                OnCancel(playerIndex);
        } // HandleInput

        /// <summary>
        /// Handler for when the user has chosen a menu entry.
        /// </summary>
        protected virtual void OnSelectEntry(int entryIndex, PlayerIndex playerIndex)
        {
            _OnSelectEntrySound.Play();
            menuEntries[selectedEntry].OnSelectEntry(playerIndex);
        } // OnSelectEntry

        /// <summary>
        /// Handler for when the user has cancelled the menu.
        /// </summary>
        protected virtual void OnCancel(PlayerIndex playerIndex)
        {
            ExitScreen();
        } // OnCancel

        /// <summary>
        /// Helper overload makes it easy to use OnCancel as a MenuEntry event handler.
        /// </summary>
        protected void OnCancel(object sender, PlayerIndexEventArgs e)
        {
            OnCancel(e.PlayerIndex);
        } // OnCancel

        /// <summary>
        /// Updates the menu.
        /// </summary>
        public override void Update(GameTime gameTime, bool otherScreenHasFocus, bool coveredByOtherScreen)
        {
            base.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen);

            // Update each nested MenuEntry object.
            for (int i = 0; i < menuEntries.Count; i++)
            {
                bool isSelected = IsActive && (i == selectedEntry);

                menuEntries[i].Update(this, isSelected, gameTime);
            }
        } // Update

        /// <summary>
        /// Draws the menu.
        /// </summary>
        public override void Draw(GameTime gameTime)
        {
            SpriteBatch spriteBatch = ScreenManager.SpriteBatch;
            SpriteFont font = ScreenManager.Font;

            Vector2 position = new Vector2(100, 170);

            // Make the menu slide into place during transitions, using a
            // power curve to make things look more interesting (this makes
            // the movement slow down as it nears the end).
            float transitionOffset = (float)Math.Pow(TransitionPosition, 2);

            if (ScreenState == ScreenState.TransitionOn)
                position.X -= transitionOffset * 256;
            else
                position.X += transitionOffset * 512;

            byte fade = TransitionAlpha;

            spriteBatch.Begin();

            // Draw each menu entry in turn.
            for (int i = 0; i < menuEntries.Count; i++)
            {
                MenuEntry menuEntry = menuEntries[i];

                bool isSelected = IsActive && (i == selectedEntry);

                menuEntry.Draw(this, position, isSelected, gameTime);

                position.Y += menuEntry.GetHeight(this);
            } // for

            // Draw the menu title.
            Vector2 titlePosition = new Vector2(70, 80);
            Vector2 titleOrigin = new Vector2(0, 0); //font.MeasureString(menuTitle) / 2;
            Color titleColor = new Color(192, 192, 192, TransitionAlpha);
            float titleScale = 1.25f;

            titlePosition.Y -= transitionOffset * 100;

            spriteBatch.Draw(titleBackgroundTexture,
                new Vector2(titlePosition.X - 60, titlePosition.Y + font.MeasureString(menuTitle).Y / 2 - titleBackgroundTexture.Height / 2),
                new Color(fade, fade, fade));
            spriteBatch.DrawString(font, menuTitle, titlePosition, titleColor, 0,
                                   titleOrigin, titleScale, SpriteEffects.None, 0);

            spriteBatch.End();
        } // Draw
    } // class MenuScreen
} // namespace XnaGameFramework.GameStateManagement
